home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / PRG / MacPerl 506 appl folder.sit / MacPerl 506 appl folder / Mac_Perl_506r1m_appl / lib / bigint.pl < prev    next >
Perl Script  |  1995-03-19  |  8KB  |  276 lines

  1. package bigint;
  2.  
  3. # arbitrary size integer math package
  4. #
  5. # by Mark Biggar
  6. #
  7. # Canonical Big integer value are strings of the form
  8. #       /^[+-]¥d+$/ with leading zeros suppressed
  9. # Input values to these routines may be strings of the form
  10. #       /^¥s*[+-]?[¥d¥s]+$/.
  11. # Examples:
  12. #   '+0'                            canonical zero value
  13. #   '   -123 123 123'               canonical value '-123123123'
  14. #   '1 23 456 7890'                 canonical value '+1234567890'
  15. # Output values always always in canonical form
  16. #
  17. # Actual math is done in an internal format consisting of an array
  18. #   whose first element is the sign (/^[+-]$/) and whose remaining 
  19. #   elements are base 100000 digits with the least significant digit first.
  20. # The string 'NaN' is used to represent the result when input arguments 
  21. #   are not numbers, as well as the result of dividing by zero
  22. #
  23. # routines provided are:
  24. #
  25. #   bneg(BINT) return BINT              negation
  26. #   babs(BINT) return BINT              absolute value
  27. #   bcmp(BINT,BINT) return CODE         compare numbers (undef,<0,=0,>0)
  28. #   badd(BINT,BINT) return BINT         addition
  29. #   bsub(BINT,BINT) return BINT         subtraction
  30. #   bmul(BINT,BINT) return BINT         multiplication
  31. #   bdiv(BINT,BINT) return (BINT,BINT)  division (quo,rem) just quo if scalar
  32. #   bmod(BINT,BINT) return BINT         modulus
  33. #   bgcd(BINT,BINT) return BINT         greatest common divisor
  34. #   bnorm(BINT) return BINT             normalization
  35. #
  36.  
  37. $zero = 0;
  38.  
  39. # normalize string form of number.   Strip leading zeros.  Strip any
  40. #   white space and add a sign, if missing.
  41. # Strings that are not numbers result the value 'NaN'.
  42.  
  43. sub main'bnorm { #(num_str) return num_str
  44.     local($_) = @_;
  45.     s/¥s+//g;                           # strip white space
  46.     if (s/^([+-]?)0*(¥d+)$/$1$2/) {     # test if number
  47.     substr($_,$[,0) = '+' unless $1; # Add missing sign
  48.     s/^-0/+0/;
  49.     $_;
  50.     } else {
  51.     'NaN';
  52.     }
  53. }
  54.  
  55. # Convert a number from string format to internal base 100000 format.
  56. #   Assumes normalized value as input.
  57. sub internal { #(num_str) return int_num_array
  58.     local($d) = @_;
  59.     ($is,$il) = (substr($d,$[,1),length($d)-2);
  60.     substr($d,$[,1) = '';
  61.     ($is, reverse(unpack("a" . ($il%5+1) . ("a5" x ($il/5)), $d)));
  62. }
  63.  
  64. # Convert a number from internal base 100000 format to string format.
  65. #   This routine scribbles all over input array.
  66. sub external { #(int_num_array) return num_str
  67.     $es = shift;
  68.     grep($_ > 9999 || ($_ = substr('0000'.$_,-5)), @_);   # zero pad
  69.     &'bnorm(join('', $es, reverse(@_)));    # reverse concat and normalize
  70. }
  71.  
  72. # Negate input value.
  73. sub main'bneg { #(num_str) return num_str
  74.     local($_) = &'bnorm(@_);
  75.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0';
  76.     s/^H/N/;
  77.     $_;
  78. }
  79.  
  80. # Returns the absolute value of the input.
  81. sub main'babs { #(num_str) return num_str
  82.     &abs(&'bnorm(@_));
  83. }
  84.  
  85. sub abs { # post-normalized abs for internal use
  86.     local($_) = @_;
  87.     s/^-/+/;
  88.     $_;
  89. }
  90. # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
  91. sub main'bcmp { #(num_str, num_str) return cond_code
  92.     local($x,$y) = (&'bnorm($_[$[]),&'bnorm($_[$[+1]));
  93.     if ($x eq 'NaN') {
  94.     undef;
  95.     } elsif ($y eq 'NaN') {
  96.     undef;
  97.     } else {
  98.     &cmp($x,$y);
  99.     }
  100. }
  101.  
  102. sub cmp { # post-normalized compare for internal use
  103.     local($cx, $cy) = @_;
  104.     $cx cmp $cy
  105.     &&
  106.     (
  107.     ord($cy) <=> ord($cx)
  108.     ||
  109.     ($cx cmp ',') * (length($cy) <=> length($cx) || $cy cmp $cx)
  110.     );
  111. }
  112.  
  113. sub main'badd { #(num_str, num_str) return num_str
  114.     local(*x, *y); ($x, $y) = (&'bnorm($_[$[]),&'bnorm($_[$[+1]));
  115.     if ($x eq 'NaN') {
  116.     'NaN';
  117.     } elsif ($y eq 'NaN') {
  118.     'NaN';
  119.     } else {
  120.     @x = &internal($x);             # convert to internal form
  121.     @y = &internal($y);
  122.     local($sx, $sy) = (shift @x, shift @y); # get signs
  123.     if ($sx eq $sy) {
  124.         &external($sx, &add(*x, *y)); # if same sign add
  125.     } else {
  126.         ($x, $y) = (&abs($x),&abs($y)); # make abs
  127.         if (&cmp($y,$x) > 0) {
  128.         &external($sy, &sub(*y, *x));
  129.         } else {
  130.         &external($sx, &sub(*x, *y));
  131.         }
  132.     }
  133.     }
  134. }
  135.  
  136. sub main'bsub { #(num_str, num_str) return num_str
  137.     &'badd($_[$[],&'bneg($_[$[+1]));    
  138. }
  139.  
  140. # GCD -- Euclids algorithm Knuth Vol 2 pg 296
  141. sub main'bgcd { #(num_str, num_str) return num_str
  142.     local($x,$y) = (&'bnorm($_[$[]),&'bnorm($_[$[+1]));
  143.     if ($x eq 'NaN' || $y eq 'NaN') {
  144.     'NaN';
  145.     } else {
  146.     ($x, $y) = ($y,&'bmod($x,$y)) while $y ne '+0';
  147.     $x;
  148.     }
  149. }
  150. # routine to add two base 1e5 numbers
  151. #   stolen from Knuth Vol 2 Algorithm A pg 231
  152. #   there are separate routines to add and sub as per Kunth pg 233
  153. sub add { #(int_num_array, int_num_array) return int_num_array
  154.     local(*x, *y) = @_;
  155.     $car = 0;
  156.     for $x (@x) {
  157.     last unless @y || $car;
  158.     $x -= 1e5 if $car = (($x += shift(@y) + $car) >= 1e5);
  159.     }
  160.     for $y (@y) {
  161.     last unless $car;
  162.     $y -= 1e5 if $car = (($y += $car) >= 1e5);
  163.     }
  164.     (@x, @y, $car);
  165. }
  166.  
  167. # subtract base 1e5 numbers -- stolen from Knuth Vol 2 pg 232, $x > $y
  168. sub sub { #(int_num_array, int_num_array) return int_num_array
  169.     local(*sx, *sy) = @_;
  170.     $bar = 0;
  171.     for $sx (@sx) {
  172.     last unless @y || $bar;
  173.     $sx += 1e5 if $bar = (($sx -= shift(@sy) + $bar) < 0);
  174.     }
  175.     @sx;
  176. }
  177.  
  178. # multiply two numbers -- stolen from Knuth Vol 2 pg 233
  179. sub main'bmul { #(num_str, num_str) return num_str
  180.     local(*x, *y); ($x, $y) = (&'bnorm($_[$[]), &'bnorm($_[$[+1]));
  181.     if ($x eq 'NaN') {
  182.     'NaN';
  183.     } elsif ($y eq 'NaN') {
  184.     'NaN';
  185.     } else {
  186.     @x = &internal($x);
  187.     @y = &internal($y);
  188.     local($signr) = (shift @x ne shift @y) ? '-' : '+';
  189.     @prod = ();
  190.     for $x (@x) {
  191.         ($car, $cty) = (0, $[);
  192.         for $y (@y) {
  193.         $prod = $x * $y + $prod[$cty] + $car;
  194.         $prod[$cty++] =
  195.             $prod - ($car = int($prod * 1e-5)) * 1e5;
  196.         }
  197.         $prod[$cty] += $car if $car;
  198.         $x = shift @prod;
  199.     }
  200.     &external($signr, @x, @prod);
  201.     }
  202. }
  203.  
  204. # modulus
  205. sub main'bmod { #(num_str, num_str) return num_str
  206.     (&'bdiv(@_))[$[+1];
  207. }
  208. sub main'bdiv { #(dividend: num_str, divisor: num_str) return num_str
  209.     local (*x, *y); ($x, $y) = (&'bnorm($_[$[]), &'bnorm($_[$[+1]));
  210.     return wantarray ? ('NaN','NaN') : 'NaN'
  211.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0');
  212.     return wantarray ? ('+0',$x) : '+0' if (&cmp(&abs($x),&abs($y)) < 0);
  213.     @x = &internal($x); @y = &internal($y);
  214.     $srem = $y[$[];
  215.     $sr = (shift @x ne shift @y) ? '-' : '+';
  216.     $car = $bar = $prd = 0;
  217.     if (($dd = int(1e5/($y[$#y]+1))) != 1) {
  218.     for $x (@x) {
  219.         $x = $x * $dd + $car;
  220.         $x -= ($car = int($x * 1e-5)) * 1e5;
  221.     }
  222.     push(@x, $car); $car = 0;
  223.     for $y (@y) {
  224.         $y = $y * $dd + $car;
  225.         $y -= ($car = int($y * 1e-5)) * 1e5;
  226.     }
  227.     }
  228.     else {
  229.     push(@x, 0);
  230.     }
  231.     @q = (); ($v2,$v1) = @y[-2,-1];
  232.     while ($#x > $#y) {
  233.     ($u2,$u1,$u0) = @x[-3..-1];
  234.     $q = (($u0 == $v1) ? 99999 : int(($u0*1e5+$u1)/$v1));
  235.     --$q while ($v2*$q > ($u0*1e5+$u1-$q*$v1)*1e5+$u2);
  236.     if ($q) {
  237.         ($car, $bar) = (0,0);
  238.         for ($y = $[, $x = $#x-$#y+$[-1; $y <= $#y; ++$y,++$x) {
  239.         $prd = $q * $y[$y] + $car;
  240.         $prd -= ($car = int($prd * 1e-5)) * 1e5;
  241.         $x[$x] += 1e5 if ($bar = (($x[$x] -= $prd + $bar) < 0));
  242.         }
  243.         if ($x[$#x] < $car + $bar) {
  244.         $car = 0; --$q;
  245.         for ($y = $[, $x = $#x-$#y+$[-1; $y <= $#y; ++$y,++$x) {
  246.             $x[$x] -= 1e5
  247.             if ($car = (($x[$x] += $y[$y] + $car) > 1e5));
  248.         }
  249.         }   
  250.     }
  251.     pop(@x); unshift(@q, $q);
  252.     }
  253.     if (wantarray) {
  254.     @d = ();
  255.     if ($dd != 1) {
  256.         $car = 0;
  257.         for $x (reverse @x) {
  258.         $prd = $car * 1e5 + $x;
  259.         $car = $prd - ($tmp = int($prd / $dd)) * $dd;
  260.         unshift(@d, $tmp);
  261.         }
  262.     }
  263.     else {
  264.         @d = @x;
  265.     }
  266.     (&external($sr, @q), &external($srem, @d, $zero));
  267.     } else {
  268.     &external($sr, @q);
  269.     }
  270. }
  271. 1;
  272.